package com.zzx.controller;

import com.zzx.Util.*;
import com.zzx.bean.*;
import com.zzx.service.imp.CourierService;
import com.zzx.service.imp.UserService;
import com.zzx.servlet.ResponseText;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.Utilities;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: Spider Man
 * @Description:
 * @Date Created in 2020-09-16 11:37
 * @Modified By:
 */
public class UserController {

    UserService userService = new UserService();

    @ResponseText("/user/console.do")
    public String console(HttpServletRequest request, HttpServletResponse response) {
        List<Map<String, Integer>> console = userService.console();
        Message message = new Message();
        if (console.size() == 0) {
            message.setStatus(-1);
            message.setResult("没有用户信息");
        } else {
            message.setStatus(0);
            message.setResult("用户信息加载成功");
            message.setData(console);
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseText("/user/list.do")
    public String list(HttpServletRequest request, HttpServletResponse response) {
        // 1. 查询数据的起始索引值
        int offset = Integer.parseInt(request.getParameter("offset"));
        // 2. 当前页需要查询的数据量
        int pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
        // 3. 查询
        List<User> list = userService.findAllUserInfo(true, offset, pageNumber);
        List<Map<String, Integer>> console = userService.console();
        List<BootstrapTableUser> list1 = new ArrayList<>();
        for (User user : list) {
            String uRegisterTime = DateFormatUtil.format(user.getuRegisterTime());
            String uLoginTime = user.getuLoginTime() == null ? "暂未登录" : DateFormatUtil.format(user.getuLoginTime());
            BootstrapTableUser bootstrapTableUser = new BootstrapTableUser(user.getUid(), user.getuName(),
                    user.getuPhone(), user.getuIdentity(), user.getuPassword(), uRegisterTime, uLoginTime);
            list1.add(bootstrapTableUser);
        }
        Integer total = console.get(0).get("size");
        // 4. 将list封装为bootstrap-table能够识别的格式
        ResultData<BootstrapTableUser> data = new ResultData<>();
        data.setRows(list1);
        data.setTotal(total);
        return JSONUtil.toJSON(data);
    }

    @ResponseText("/user/add.do")
    public String add(HttpServletRequest request, HttpServletResponse response){
        String uName = request.getParameter("uName");
        String uPhone = request.getParameter("uPhone");
        String uIdentity = request.getParameter("uIdentity");
        String uPassword = request.getParameter("uPassword");
        User user = new User(uName,uPhone,uIdentity,uPassword);
        boolean flag = userService.insert(user);
        Message message = new Message();
        if (flag && !uIdentity.equals("")){
            message.setStatus(0);
            message.setResult("添加成功");
        }else {
            message.setStatus(-1);
            message.setResult("添加失败");
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseText("/user/find.do")
    public String find(HttpServletRequest request, HttpServletResponse response){
        String uPhone = request.getParameter("uPhone");
        User userByCPhone = userService.findUserByUPhone(uPhone);
        Message message = new Message();
        if (userByCPhone == null){
            message.setStatus(-1);
            message.setResult("该手机号不存在");
        }else {
            message.setStatus(0);
            message.setResult("查询成功");
            message.setData(userByCPhone);
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseText("/user/update.do")
    public String update(HttpServletRequest request, HttpServletResponse response){
        int uid = Integer.parseInt(request.getParameter("uid"));
        String uName = request.getParameter("uName");
        String uPhone = request.getParameter("uPhone");
        String uIdentity = request.getParameter("uIdentity");
        String uPassword = request.getParameter("uPassword");
        User user = new User(uName,uPhone,uIdentity,uPassword);
        boolean flag = userService.update(uid, user);
        Message message = new Message();
        if (flag){
            message.setStatus(0);
            message.setResult("修改成功");
            message.setData(uid);
        }else {
            message.setStatus(-1);
            message.setResult("修改失败");
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseText("/user/delete.do")
    public String delete(HttpServletRequest request, HttpServletResponse response){
        Integer uid = Integer.valueOf(request.getParameter("uid"));
        boolean flag = userService.delete(uid);
        Message message = new Message();
        if (flag){
            message.setStatus(0);
            message.setResult("删除成功");
        }else {
            message.setStatus(-1);
            message.setResult("删除失败");
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseText("/wx/loginSms.do")
    public String loginSms(HttpServletRequest request, HttpServletResponse response){
        String uPhone = request.getParameter("uPhone");
        String code = RandomUtil.createCode()+"";
        //boolean flag = SMSUtil.sendCodeForWxLogin(uPhone, code);
        boolean flag = true;
        Message message = new Message();
        if (flag){
            message.setStatus(0);
            message.setResult("验证码已发送，请查收");
        }else {
            message.setStatus(-1);
            message.setResult("验证码发送失败，请检查手机号或稍后再试");
        }
//        UserUtil.setLoginSms(request.getSession(),uPhone,code);
        UserUtil.setLoginSms(request.getSession(),uPhone,"123456");
        return JSONUtil.toJSON(message);
    }

    @ResponseText("/wx/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response){
        boolean userIdentity = false;
        String uPhone = request.getParameter("uPhone");
        String code = request.getParameter("code");
        String sysCode = UserUtil.loginSms(request.getSession(), uPhone);
        CourierService courierService = new CourierService();
        Message message = new Message();
        User user = new User();
        user.setuPhone(uPhone);
        if (sysCode == null){
            //该手机号还未获取短信
            message.setStatus(-1);
            message.setResult("该手机号码未获取验证码");
        }else if (sysCode.equals(code)){
            //验证通过
            if (courierService.findCourierByCPhone(uPhone) != null){
                // 说明是快递员
                message.setStatus(1);
                userIdentity = true;
            }else if (userService.findUserByUPhone(uPhone) != null){
                message.setStatus(0);
            }else {
                userService.insert(user);
                message.setStatus(0);
            }
            UserUtil.setWxUser(request.getSession(),user,userIdentity);
        }else {
            //验证失败
            message.setStatus(-2);
            message.setResult("验证码有误，请检查");
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseText("/wx/logout.do")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        request.getSession().invalidate();
        Message message = new Message(0);
        return JSONUtil.toJSON(message);
    }

    @ResponseText("/wx/userInfo.do")
    public String userInfo(HttpServletRequest request, HttpServletResponse response){
        User user = UserUtil.getWxUser(request.getSession());
        Boolean userInfo = UserUtil.getUserInfo(request.getSession());
        Message message = new Message();
        try {
            if (userInfo){
                //是快递员
                message.setStatus(1);
            }else {
                //是用户
                message.setStatus(0);
            }
            message.setResult(user.getuPhone());
        }catch (NullPointerException e){
            message.setResult("身份信息异常，请重新操作");
        }
        return JSONUtil.toJSON(message);
    }
}
